﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;

namespace SmartProject.Entity
{
    /// <summary>
    /// The File-type entity class defines the type of file that is handled.
    /// </summary>
    public class FileType : EntityBase
    {
        /// <summary>
        /// Gets or sets the name/ description of the file-type.
        /// </summary>
        public virtual string Description { get; set; }

        /// <summary>
        /// Gets or sets the file-type extension.
        /// </summary>
        public virtual string Extension { get; set; }

        public static FileType GetFileTypeByFileExtension(ISession session, string extension)
        {
            IList<ICriterion> expressions = new List<ICriterion>();
            expressions.Add(Restrictions.Eq("Extension", extension));
            IList<EntityBase> entities = Find(session, expressions, null, typeof(FileType));
            if (entities != null && entities.Count == 1)
            {
                return (FileType)entities[0];
            }
            return null;
        }

        public static FileType GetFileTypeByFileName(ISession session, string filename)
        {
            System.IO.FileInfo info = new System.IO.FileInfo(filename);
            return GetFileTypeByFileExtension(session, info.Extension.Replace(".", "").ToLower());
        }

        public static string GetMimeType(string fileType)
        {
            switch (fileType)
            {
                case "jpg":
                    return "image/jpeg";

                case "png":
                    return "image/png";

                case "txt":
                    return "text/txt";

                case "doc":
                    return "application/msword";

                case "xml":
                    return "text/xml";
            }
            return String.Empty;
        }

        /// <summary>
        /// Gets whether this file-type is an image file.
        /// </summary>
        public virtual bool IsImageFile
        {
            get
            {
                switch (Extension)
                {
                    case "jpg":
                        return true;

                    case "png":
                        return true;

                    default:
                        return false;
                }
            }
        }

        /// <summary>
        /// Get file-type by file-type Id.
        /// </summary>
        /// <param name="session">Session used in this request.</param>
        /// <param name="fileTypeId">File-type Id.</param>
        /// <returns>FileType.</returns>
        public static FileType GetFileType(ISession session, int fileTypeId)
        {
            return (FileType)EntityBase.GetEntity(session, fileTypeId, typeof(FileType));
        }
    }
}
